<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <SearchForm
      v-model="searchForm"
      :inline="true"
      label-width="80px"
      @search="handleSearch"
      @reset="handleReset"
    >
      <el-form-item label="等级名称">
        <el-input v-model="searchForm.name" placeholder="请输入等级名称" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
          <el-option label="启用" value="ACTIVE" />
          <el-option label="禁用" value="INACTIVE" />
        </el-select>
      </el-form-item>
    </SearchForm>
    
    <!-- 统计卡片 -->
    <div class="stats-container">
      <StatCard
        title="会员等级数"
        :value="statistics.totalLevels || 0"
        icon="Medal"
        type="primary"
      />
      <StatCard
        title="会员总数"
        :value="statistics.totalMembers || 0"
        icon="UserFilled"
        type="success"
        :trend="statistics.memberGrowth"
      />
      <StatCard
        title="今日新增会员"
        :value="statistics.todayNewMembers || 0"
        icon="UserFilled"
        type="warning"
      />
      <StatCard
        title="会员收入"
        :value="statistics.totalRevenue || 0"
        icon="Wallet"
        type="danger"
      />
    </div>
    
    <!-- 会员等级表格 -->
    <Card title="会员等级列表">
      <template #extra>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增等级
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </template>
      
      <CommonTable
        ref="tableRef"
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @sort-change="handleSortChange"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
        <template #status="{ row }">
          <el-tag :type="row.status === 'ACTIVE' ? 'success' : 'danger'">
            {{ row.status === 'ACTIVE' ? '启用' : '禁用' }}
          </el-tag>
        </template>
        
        <template #price="{ row }">
          <span>¥{{ row.price }}</span>
        </template>
        
        <template #duration="{ row }">
          <span>{{ row.duration }}天</span>
        </template>
        
        <template #action="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="primary" link @click="handleViewOrders(row)">
            <el-icon><Tickets /></el-icon>
            查看订单
          </el-button>
          <el-button 
            type="primary" 
            link 
            @click="handleToggleStatus(row)"
          >
            <el-icon><Switch /></el-icon>
            {{ row.status === 'ACTIVE' ? '禁用' : '启用' }}
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </CommonTable>
    </Card>
    
    <!-- 会员等级表单对话框 -->
    <CommonDialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增会员等级' : '编辑会员等级'"
      width="600px"
      @confirm="handleSubmit"
      @cancel="handleCancel"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="等级名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入等级名称" />
        </el-form-item>
        <el-form-item label="等级描述" prop="description">
          <el-input 
            v-model="formData.description" 
            type="textarea" 
            placeholder="请输入等级描述" 
            :rows="3" 
          />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number 
            v-model="formData.price" 
            :min="0" 
            :precision="2" 
            placeholder="请输入价格" 
          />
        </el-form-item>
        <el-form-item label="有效期" prop="duration">
          <el-input-number 
            v-model="formData.duration" 
            :min="1" 
            placeholder="请输入有效期（天）" 
          />
        </el-form-item>
        <el-form-item label="配额数量" prop="quotaAmount">
          <el-input-number 
            v-model="formData.quotaAmount" 
            :min="0" 
            placeholder="请输入配额数量" 
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number 
            v-model="formData.sort" 
            :min="0" 
            placeholder="请输入排序" 
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="ACTIVE">启用</el-radio>
            <el-radio label="INACTIVE">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权益说明" prop="benefits">
          <el-input 
            v-model="formData.benefits" 
            type="textarea" 
            placeholder="请输入权益说明" 
            :rows="4" 
          />
        </el-form-item>
      </el-form>
    </CommonDialog>
    
    <!-- 会员订单对话框 -->
    <CommonDialog
      v-model="orderVisible"
      title="会员订单"
      width="1000px"
      :show-footer="false"
    >
      <div class="order-container">
        <div class="order-header">
          <div class="level-info">
            <span>等级名称: {{ currentLevel.name }}</span>
            <span>价格: ¥{{ currentLevel.price }}</span>
            <span>有效期: {{ currentLevel.duration }}天</span>
          </div>
          <div class="order-actions">
            <el-button @click="refreshOrders" :loading="orderLoading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
        
        <CommonTable
          :data="orders"
          :columns="orderColumns"
          :loading="orderLoading"
          :show-pagination="false"
          :max-height="400"
        >
          <template #status="{ row }">
            <el-tag :type="getOrderStatusColor(row.status)">
              {{ getOrderStatusLabel(row.status) }}
            </el-tag>
          </template>
          
          <template #amount="{ row }">
            <span>¥{{ row.amount }}</span>
          </template>
          
          <template #action="{ row }">
            <el-button type="primary" link @click="handleViewOrderDetail(row)">
              <el-icon><View /></el-icon>
              查看详情
            </el-button>
          </template>
        </CommonTable>
      </div>
    </CommonDialog>
    
    <!-- 订单详情对话框 -->
    <CommonDialog
      v-model="orderDetailVisible"
      title="订单详情"
      width="600px"
      :show-footer="false"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{ orderDetail.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ orderDetail.username }}</el-descriptions-item>
        <el-descriptions-item label="会员等级">{{ orderDetail.levelName }}</el-descriptions-item>
        <el-descriptions-item label="金额">
          <span>¥{{ orderDetail.amount }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ orderDetail.paymentMethod || '-' }}</el-descriptions-item>
        <el-descriptions-item label="交易号">{{ orderDetail.transactionNo || '-' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getOrderStatusColor(orderDetail.status)">
            {{ getOrderStatusLabel(orderDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ orderDetail.createTime }}</el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ orderDetail.paymentTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ orderDetail.startTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="到期时间">{{ orderDetail.endTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          {{ orderDetail.remark || '-' }}
        </el-descriptions-item>
      </el-descriptions>
    </CommonDialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMemberLevelList, getMemberLevelDetail, createMemberLevel, updateMemberLevel, deleteMemberLevel, updateMemberLevelStatus, getMemberStatistics, getMemberOrderList, getMemberOrderDetail } from '@/api/member'
import { useTable } from '@/hooks/useTable'
import { useForm } from '@/hooks/useForm'
import { useDialog } from '@/hooks/useDialog'

// 表格列配置
const columns = [
  {
    prop: 'id',
    label: 'ID',
    width: '80'
  },
  {
    prop: 'name',
    label: '等级名称',
    minWidth: '120'
  },
  {
    prop: 'description',
    label: '等级描述',
    minWidth: '180'
  },
  {
    prop: 'price',
    label: '价格',
    width: '120',
    slot: 'price'
  },
  {
    prop: 'duration',
    label: '有效期',
    width: '120',
    slot: 'duration'
  },
  {
    prop: 'quotaAmount',
    label: '配额数量',
    width: '120'
  },
  {
    prop: 'sort',
    label: '排序',
    width: '80'
  },
  {
    prop: 'status',
    label: '状态',
    width: '100',
    slot: 'status'
  },
  {
    prop: 'createTime',
    label: '创建时间',
    width: '180',
    sortable: 'custom'
  },
  {
    prop: 'action',
    label: '操作',
    width: '280',
    slot: 'action',
    fixed: 'right'
  }
]

// 订单表格列配置
const orderColumns = [
  {
    prop: 'orderNo',
    label: '订单号',
    width: '180'
  },
  {
    prop: 'username',
    label: '用户名',
    minWidth: '120'
  },
  {
    prop: 'amount',
    label: '金额',
    width: '120',
    slot: 'amount'
  },
  {
    prop: 'status',
    label: '状态',
    width: '100',
    slot: 'status'
  },
  {
    prop: 'paymentMethod',
    label: '支付方式',
    width: '120'
  },
  {
    prop: 'createTime',
    label: '创建时间',
    width: '180'
  },
  {
    prop: 'action',
    label: '操作',
    width: '100',
    slot: 'action',
    fixed: 'right'
  }
]

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 统计数据
const statistics = reactive({
  totalLevels: 0,
  totalMembers: 0,
  todayNewMembers: 0,
  totalRevenue: 0,
  memberGrowth: 0
})

// 表格相关
const {
  tableData,
  loading,
  pagination,
  loadData,
  handleSortChange,
  handleSizeChange,
  handleCurrentChange
} = useTable(getMemberLevelList, {
  defaultParams: searchForm,
  immediate: false
})

// 表单相关
const defaultFormData = {
  name: '',
  description: '',
  price: 0,
  duration: 30,
  quotaAmount: 0,
  sort: 0,
  status: 'ACTIVE',
  benefits: ''
}

const formRules = {
  name: [
    { required: true, message: '请输入等级名称', trigger: 'blur' },
    { min: 2, max: 20, message: '等级名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入等级描述', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能小于0', trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '请输入有效期', trigger: 'blur' },
    { type: 'number', min: 1, message: '有效期不能小于1天', trigger: 'blur' }
  ],
  quotaAmount: [
    { required: true, message: '请输入配额数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '配额数量不能小于0', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

const {
  formData,
  formRef,
  submitting,
  resetForm,
  validateForm,
  submitForm
} = useForm(defaultFormData, handleSubmit, {
  resetAfterSubmit: false
})

// 对话框相关
const {
  visible: dialogVisible,
  showDialog,
  hideDialog
} = useDialog()

const {
  visible: orderVisible,
  showDialog: showOrderDialog,
  hideDialog: hideOrderDialog
} = useDialog()

const {
  visible: orderDetailVisible,
  showDialog: showOrderDetailDialog,
  hideDialog: hideOrderDetailDialog
} = useDialog()

// 其他变量
const tableRef = ref(null)
const dialogType = ref('add')
const currentLevel = reactive({})
const orders = ref([])
const orderLoading = ref(false)
const orderDetail = reactive({})

// 获取统计数据
const getStatisticsData = async () => {
  try {
    const response = await getMemberStatistics()
    if (response) {
      Object.assign(statistics, response)
    }
  } catch (error) {
    console.error('获取统计数据失败', error)
  }
}

// 获取订单状态颜色
const getOrderStatusColor = (status) => {
  const colors = {
    PENDING: 'warning',
    PAID: 'success',
    CANCELLED: 'info',
    REFUNDED: 'danger'
  }
  return colors[status] || 'info'
}

// 获取订单状态标签
const getOrderStatusLabel = (status) => {
  const labels = {
    PENDING: '待支付',
    PAID: '已支付',
    CANCELLED: '已取消',
    REFUNDED: '已退款'
  }
  return labels[status] || status
}

// 处理搜索
const handleSearch = () => {
  loadData(searchForm)
}

// 处理重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    status: ''
  })
  handleSearch()
}

// 处理新增
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  showDialog()
}

// 处理编辑
const handleEdit = async (row) => {
  try {
    const response = await getMemberLevelDetail(row.id)
    if (response) {
      dialogType.value = 'edit'
      Object.assign(formData, response)
      showDialog()
    }
  } catch (error) {
    console.error('获取会员等级详情失败', error)
  }
}

// 处理查看订单
const handleViewOrders = async (row) => {
  try {
    Object.assign(currentLevel, row)
    orders.value = []
    showOrderDialog()
    await loadOrders(row.id)
  } catch (error) {
    console.error('加载订单失败', error)
  }
}

// 加载订单
const loadOrders = async (levelId) => {
  try {
    orderLoading.value = true
    const response = await getMemberOrderList({ levelId })
    if (response && response.data) {
      orders.value = response.data.records || response.data || []
    }
  } catch (error) {
    console.error('获取订单失败', error)
  } finally {
    orderLoading.value = false
  }
}

// 刷新订单
const refreshOrders = async () => {
  await loadOrders(currentLevel.id)
}

// 处理查看订单详情
const handleViewOrderDetail = async (row) => {
  try {
    const response = await getMemberOrderDetail(row.id)
    if (response) {
      Object.assign(orderDetail, response)
      showOrderDetailDialog()
    }
  } catch (error) {
    console.error('获取订单详情失败', error)
  }
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除会员等级 "${row.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteMemberLevel(row.id)
      ElMessage.success('删除成功')
      loadData()
      getStatisticsData()
    } catch (error) {
      console.error('删除失败', error)
    }
  }).catch(() => {})
}

// 处理切换状态
const handleToggleStatus = (row) => {
  const newStatus = row.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'
  const statusText = newStatus === 'ACTIVE' ? '启用' : '禁用'
  
  ElMessageBox.confirm(
    `确定要${statusText}会员等级 "${row.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await updateMemberLevelStatus(row.id, newStatus)
      ElMessage.success(`${statusText}成功`)
      loadData()
      getStatisticsData()
    } catch (error) {
      console.error(`${statusText}失败`, error)
    }
  }).catch(() => {})
}

// 处理导出
const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

// 处理表单提交
async function handleSubmit() {
  try {
    if (dialogType.value === 'add') {
      await createMemberLevel(formData)
      ElMessage.success('新增成功')
    } else {
      await updateMemberLevel(formData.id, formData)
      ElMessage.success('更新成功')
    }
    
    hideDialog()
    loadData()
    getStatisticsData()
  } catch (error) {
    console.error('提交失败', error)
  }
}

// 处理取消
const handleCancel = () => {
  hideDialog()
}

onMounted(() => {
  loadData()
  getStatisticsData()
})
</script>

<style lang="scss" scoped>
.app-container {
  .stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
  }
  
  .order-container {
    .order-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px;
      border-bottom: 1px solid var(--el-border-color-lighter);
      margin-bottom: 16px;
      
      .level-info {
        display: flex;
        gap: 16px;
        
        span {
          font-size: 14px;
          color: var(--el-text-color-regular);
        }
      }
    }
  }
}
</style>